package com.itheima.service.impl;

import com.css.tliasspringbootstarterautoconfigure.utils.JwtUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpService;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private EmpMapper empMapper;
    @Override
    public PageBean findPage(LimitConditons limitConditons) {
//        //total
//        Integer count=empMapper.findCount();
//        //rows
//        //计算起始索引
//        Integer index=(limitConditons.getPage()-1)*limitConditons.getPageSize();
//        limitConditons.setPage(index);
//        List<Emp> empList=empMapper.findPage(limitConditons);
//        //封装
//        PageBean pageBean = new PageBean(count, empList);
//        return pageBean;

        PageBean pageBean = new PageBean();
        //========使用PageHelper
        PageHelper pageHelper = new PageHelper();
        //设置插件的参数，当前页，每页记录数
        PageHelper.startPage(limitConditons.getPage(),limitConditons.getPageSize());
        //查询全部数据,带条件查询
        List<Emp> empList=empMapper.findPage(limitConditons);
        //把查询结果强转成Page
        Page<Emp> p=(Page<Emp>) empList;
        System.out.println(p.getResult());
        //从page中获得total和rows
       pageBean.setTotal(p.getTotal());
       pageBean.setRows(p.getResult());

       return pageBean;
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        empMapper.deleteByIds(ids);
    }

    @Override
    public void add(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.add(emp);
    }

    @Override
    public Emp findById(Integer id) {
        Emp emp=empMapper.findById(id);
        return emp;
    }

    @Override
    public void updateById(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);
    }

    @Override
    public Result login(Emp emp) {
        //调用mapper层获取empList集合
        Emp emp1=empMapper.login(emp);
        //验证账户密码是否正确，如果正确生成jwt返回

            if(emp1!=null){
                //生成载荷
                Map<String, Object> claims = new HashMap<>();
                claims.put("username",emp1.getUsername());
                claims.put("password",emp1.getPassword());
                //生成jwt
                String jwt = jwtUtils.generateJwt(claims);
                return Result.success(jwt);
            }

        return Result.error("账号名或密码错误");
    }
}
